<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle" :class="{active:show}">
      <span v-if="!fullLocation" class="placeholder">请选择配送地址</span>
      <span v-else class="value">{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="show">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span class="ellipsis" @click="changeItem(item)" v-for="item in currList" :key="item.code">{{ item.name }}</span>
      </template>
    </div>
  </div>
</template>

<script setup>
import { onClickOutside } from '@vueuse/core'
import axios from 'axios' // 直接获取公共数据

const show = ref(false)
// 定义存储地区名变量
const allCityData = ref([])
// 定义loading
const loading = ref(false)

// 提供打开和关闭的行为方法
const open = () => {
  show.value = true
  loading.value = true
  // 每次打开时调用数据
  getCityData().then(data => {
    allCityData.value = data
    loading.value = false
  })
  // 每次打开都清空之前的选择
  for (const key in selectAddress) {
    selectAddress[key] = ''
  }
}
const close = () => {
  show.value = false
}
// 提供切换函数
const toggle = () => {
  show.value ? close() : open()
}
// 点击外侧关闭对话框
const target = ref(null)
onClickOutside(target, () => {
  close()
})
// 获取省市区数据函数
const getCityData = () => {
  // 地址 https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
  // 1.当本地没有缓存则发请求，
  // 2.当本地有缓存，从缓存中取
  // 返回promise在then拿数据，因为这里既可能异步也可能同步
  return new Promise((resolve, reject) => {
    // 约定一个全局变量名存储城市数据（window的cityData字段）
    if (window.cityData) {
      resolve(window.cityData)
    } else {
      const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      axios.get(url).then(({ data }) => {
        // 缓存数据
        window.cityData = data
        resolve(data)
      })
    }
  })
}
const emit = defineEmits(['change'])
// 使用计算属性，获得当前选择地区的列表
const currList = computed(() => {
  // 默认一开始显示省一级地区
  let list = allCityData.value
  // 如果存了数据，缩小对象范围
  if (selectAddress.provinceCode && selectAddress.provinceName) {
    list = list.find(i => i.code === selectAddress.provinceCode).areaList
  }
  if (selectAddress.cityCode && selectAddress.cityName) {
    list = list.find(i => i.code === selectAddress.cityCode).areaList
  }
  return list
})
// 接受父组件传递的默认地址（登录or未登录）
defineProps({
  fullLocation: {
    type: String
  }
})
// 定义选择的省市区数据
const selectAddress = reactive({
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  countyCode: '',
  countyName: '',
  fullLocation: ''
})
// 当点击地区按钮时修改数据
const changeItem = (item) => {
  if (item.level === 0) {
    // item是省数据
    selectAddress.provinceCode = item.code
    selectAddress.provinceName = item.name
  }
  if (item.level === 1) {
    selectAddress.cityCode = item.code
    selectAddress.cityName = item.name
  }
  if (item.level === 2) {
    selectAddress.countyCode = item.code
    selectAddress.countyName = item.name
    close() // 关窗
    selectAddress.fullLocation = `${selectAddress.provinceName} ${selectAddress.cityName} ${selectAddress.countyName}`
    // 返回数据给父组件
    emit('change', selectAddress)
  }
}
</script>

<script>
export default {
  name: 'XtxCity'
}
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;

  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;

    &.active {
      background: #fff;
    }

    .placeholder {
      color: #999;
    }

    .value {
      color: #666;
      font-size: 12px;
    }

    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }

  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;

    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }

    >span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;

      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
